package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.Utlil.CodeGenerator;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.mapper.ElderMapper;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author alexis
 * @date 2025-06-07
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }



    @Autowired
    private IBedService bedService;

    @Autowired
     private  IElderService elderService;
    @Autowired
    private IContractService contractService;
    @Autowired
    ICheckInService  checkInService;
    @Autowired
    private ICheckInConfigService checkInConfigService;

  /*  @Override
    @Transactional(rollbackFor = Exception.class)
    public void CheckInElder(CheckInApplyDto dto) {
        //2.校验老人是否入住,怎么校验老人是否入住呢？使用老人的身份证号来找到老人
        String idCardNo = dto.getCheckInElderDto().getIdCardNo();
        Elder oldElder = elderService.lambdaQuery().eq(Elder::getIdCardNo, idCardNo)
                .one();
        if (oldElder!=null&&oldElder.getStatus()==1) {
            //3.说明老人已经入住直接返回
            throw new BaseException("老人已经入住");
        }

        //4.更新床为状态为已入住
        Long bedId = dto.getCheckInConfigDto().getBedId();
        Bed byId = bedService.getById(bedId);
        if (byId==null) {
            //说明没有床有问题

            throw new BaseException("没有床位");
        }
        //否则就设置床的状态，然后新增床
        byId.setBedStatus(1);
        bedService.updateById(byId);

        //5.新增或更新老人
        Elder elder = BeanUtil.toBean(dto.getCheckInElderDto(), Elder.class);
        if (oldElder!=null) {
            elder.setId(oldElder.getId());
        }
       elder.setStatus(1);
       elder.setBedId(bedId);
       elder.setBedNumber(byId.getBedNumber());
        elderService.saveOrUpdate(elder);
        //6.新增签约信息
        Contract contract = BeanUtil.toBean(dto.getCheckInContractDto(), Contract.class);
        contract.setElderId(Math.toIntExact(elder.getId()));
        contract.setContractNumber("HT"+ CodeGenerator.generateContractNumber());
        contract.setElderName(elder.getName());
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        contract.setStatus(LocalDateTime.now().isAfter(startDate)?1:0);
        contractService.save(contract);


        //7.新增入住信息
        CheckIn checkIn = BeanUtil.copyProperties(dto.getCheckInConfigDto(), CheckIn.class);
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(byId.getBedNumber());
        checkIn.setStatus(0);
        //获取家属的信息
        checkIn.setRemark(JSONUtil.toJsonStr(dto.getElderFamilyDtoList()));
        checkInService.save(checkIn);


        //8.新增入住配置
        CheckInConfig checkInConfig = BeanUtil.copyProperties(dto.getCheckInConfigDto(), CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigService.save(checkInConfig);


    }*/
    /**
     * 入住申请
     * @param dto
     */
    @Override
    public void checkinAplly(CheckInApplyDto dto) {
        //1.判断老人是否入住
        /*根据老人的身份证号来去找到老人*/
        String idCardNo = dto.getCheckInElderDto().getIdCardNo();

      /*  LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo,idCardNo);
        elderService.getOne(queryWrapper);*/
        Elder oldElder = elderService.lambdaQuery().eq(Elder::getIdCardNo, idCardNo)
                .one();
        //如果老人不为空，并且老人状态为1，说明老人已经入住，直接抛出异常
        if(oldElder!=null&&oldElder.getStatus()==1){
            throw new BaseException("老人已经入住");
        }

        //3.更新床为状态为
        /*先获取床的床号*/
        Long bedId = dto.getCheckInConfigDto().getBedId();
        //然后在查寻床
        Bed byId = bedService.getById(bedId);
        if (byId==null){
            throw new BaseException("没有床位");
        }
        byId.setBedStatus(1);
        //最后新增或者更新床位
        bedService.updateById(byId);

        //4.新增或更新老人
        //使用工具把dto转换成Elder
        Elder elder = BeanUtil.toBean(dto.getCheckInElderDto(), Elder.class);
        //如果老人不为空，就设置老人id
        if (oldElder!=null){
            elder.setId(oldElder.getId());
        }
        /*否则就新增老人根据老人表补齐所缺少的字段*/
        //设置老人状态为1
        elder.setStatus(1);
        //设置老人床id
        elder.setBedId(bedId);
        //设置床的床号
        elder.setBedNumber(byId.getBedNumber());
        elderService.saveOrUpdate(elder);
        //5.新增签约办理
        /*从dto里获取签约信息表，转换成签约表*/
        Contract contract = BeanUtil.toBean(dto.getCheckInContractDto(), Contract.class);
        //设置签约办理的老人id，剩下的就是对照签约表补齐所缺少的信息
        contract.setElderId(Math.toIntExact(elder.getId()));
        //设置签约办理的签约编号，使用工具类生成签约编号
        contract.setContractNumber("hengtong"+CodeGenerator.generateContractNumber());
        contract.setElderName(elder.getName());
        //从dto里获取配置表的时间信息，然后设置把时间设置到签约办理表
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        //设置签约办理的状态，0为未开始，1为开始
        contract.setStatus(LocalDateTime.now().isAfter(startDate)?1:0);
        contractService.save(contract);
        //6.新增入住信息
        CheckIn checkIn = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckIn.class);
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(byId.getBedNumber());
        checkIn.setStatus(0);
        checkInService.save(checkIn);
        checkIn.setRemark(JSONUtil.toJsonStr(dto.getElderFamilyDtoList()));

        //7.新增入住配置
        CheckInConfig checkInconfig = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckInConfig.class);
        checkInconfig.setCheckInId(checkIn.getId());
        checkInConfigService.save(checkInconfig);

    }


    /**
     * 获取入住详情
     * @param id
     * @return
     */

/*    @Override
    public CheckInDetailVo getCheckInDetail(Long id) {
        *//*根据入住的id查询信息*//*
        //先创建一个详情对象
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        CheckIn checkIn = checkInService.getById(id);
        //查询老人信息
        Elder elder = elderService.getById(checkIn.getElderId());
        checkInDetailVo.setCheckInElderVo(BeanUtil.toBean(elder, CheckInElderVo.class));



        //查询家属信息家属信息在入住信息里
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVoList = JSONUtil.toList(remark, ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);

        //查询入住配置信息
        CheckInConfig one1 = checkInConfigService.lambdaQuery().eq(CheckInConfig::getCheckInId, id).one();
        checkInDetailVo.setCheckInConfigVo(BeanUtil.toBean(one1, CheckInConfigVo.class));
        //查询签约信息
        Contract one = contractService.lambdaQuery().eq(Contract::getElderId, elder.getId())
                .one();
        checkInDetailVo.setContract(one);

        return checkInDetailVo;


    }*/
    /**
     * 获取入住详情
     * @param id
     * @return
     */

    @Override
    public CheckInDetailVo getCheckInDetail(Long id) {
        //根据入住id查询入住信息，new一个详情对象
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //根据入住id查询入住信息
        CheckIn checkIn = checkInService.getById(id);


        //查询老人表信息
        //首先就是查出老人的信息，然后封装到老人详情对象中
        Elder elder = elderService.getById(checkIn.getElderId());
        //把老人的属性内容赋值到checkinelderVo
        CheckInElderVo eldr = BeanUtil.toBean(elder, CheckInElderVo.class);
        checkInDetailVo.setCheckInElderVo(eldr);

        //查询家属信息
        String remark = checkIn.getRemark();
        //把字符串转换成集合
        List<ElderFamilyVo> elderFamilyVoList = JSONUtil.toList(remark, ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);


        //查询入住配置信息
        //构建查询条件构造器然后在查询
        checkInConfigService.lambdaQuery().eq(CheckInConfig::getCheckInId, id);


        //查询而签约信息
        return checkInDetailVo;


    }

}
